package com.seeyon.apps.kkSample.utils.jdbc;

import com.alibaba.fastjson.JSONObject;
import com.seeyon.ctp.util.JDBCAgent;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 适用致远链接util 失败返回null
 * @author ChengHongXi
 * @date 2023/9/25 12:11
 */
@SuppressWarnings({"unchecked"})
public class JDAgentUtil {
    private final static Log log = LogFactory.getLog(JDAgentUtil.class);

    /**
     * 查询指定列名的数据
     * @param sql        sql
     * @param params     sql set参数
     * @param columnName 需要数据库中的列名或者sql中起的别名
     * @return r
     */
    public static String querySpecify(String sql, List<Object> params, String columnName) {
        String result = null;
        List<Map<String, Object>> query;
        if (params == null || params.isEmpty()) {
            query = query(sql);
        } else {
            query = query(sql, params);
        }
        if (query != null) {
            if (query.size() > 1)
                log.warn("method:querySpecify,数据库查询时查出多条数据,sql=" + sql + ",params=" + params + ",result=" + query);
            Map<String, Object> map = query.get(0);
            Object o = map.get(columnName);
            if (o != null) result = String.valueOf(o);
        }
        return result;
    }

    /**
     * 转Object 为 String 方便处理
     * @param sql    sql
     * @param params sql参数
     * @return r
     */
    public static JSONObject queryOne(String sql, List<Object> params) {
        JSONObject result = null;
        List<Map<String, Object>> query;
        if (params == null || params.isEmpty()) {
            query = query(sql);
        } else {
            query = query(sql, params);
        }
        if (query != null) {
            if (query.size() > 1)
                log.warn("method:querySpecify,数据库查询时查出多条数据,sql=" + sql + ",params=" + params + ",result=" + query);
            Map<String, Object> map = query.get(0);
            if (map != null) {
                result = new JSONObject(map);
            }
        }
        return result;
    }

    /**
     * 转JSONObject实在影响效率 直接将查出来的原型返回
     * @param sql    sql
     * @param params sql参数
     * @return r
     */
    public static List<Map<String, Object>> queryMore(String sql, List<Object> params) {
        List<Map<String, Object>> query;
        if (params == null || params.isEmpty()) {
            query = query(sql);
        } else {
            query = query(sql, params);
        }
        return query;
    }

    /**
     * 转JSONObject 数据量大时慎用
     * @param sql    sql
     * @param params sql参数
     * @return r
     */
    public static List<JSONObject> queryMoreJSON(String sql, List<Object> params) {
        List<JSONObject> result = null;
        List<Map<String, Object>> query;
        if (params == null || params.isEmpty()) {
            query = query(sql);
        } else {
            query = query(sql, params);
        }
        if (query != null) {
            result = new ArrayList<>();
            for (Map<String, Object> map : query) {
                result.add(new JSONObject(map));
            }
        }
        return result;
    }

    /**
     * update delete insert 用这个
     * @param sql    sql
     * @param params sql参数
     * @return r
     */
    public static Integer updateMore(String sql, List<Object> params) {
        return update(sql, params);
    }

    private static List<Map<String, Object>> query(String sql, List<Object> params) {
        List<Map<String, Object>> list;
        try (JDBCAgent agent = new JDBCAgent(true, false)) {
            //1.查询操作
            agent.execute(sql, params);
            list = (List<Map<String, Object>>) agent.resultSetToList();
            Assert.notEmpty(list, "数据库未查到数据，sql=" + sql + "\nparam=" + params);
        } catch (IllegalArgumentException e) {
            log.error(e.getMessage());
            return null;
        } catch (Exception e) {
            log.error("数据库操作出错：sql=" + sql + "\nparam=" + params + e.getMessage(), e);
            return null;
        }
        return list;
    }

    private static List<Map<String, Object>> query(String sql) {
        List<Map<String, Object>> list;
        try (JDBCAgent agent = new JDBCAgent(true, false)) {
            //1.查询操作
            agent.execute(sql);
            list = (List<Map<String, Object>>) agent.resultSetToList();
            Assert.notEmpty(list, "数据库未查到数据，sql=" + sql);
        } catch (IllegalArgumentException e) {
            log.error(e.getMessage());
            return null;
        } catch (Exception e) {
            log.error("数据库操作出错：sql=" + sql + e.getMessage(), e);
            return null;
        }
        return list;
    }

    private static Integer update(String sql, List<Object> params) {
        Integer execute = null;
        try (JDBCAgent agent = new JDBCAgent(true, false)) {
            //2.更新操作
            execute = agent.execute(sql, params);
            Assert.isTrue(execute > 0, "数据库更新失败，sql=" + sql + "\nparam=" + params); // 使用isTrue方法判断数字大于0
        } catch (IllegalArgumentException e) {
            log.error(e.getMessage());
            return null;
        } catch (Exception e) {
            log.error("数据库操作出错：sql=" + sql + "\nparam=" + params + e.getMessage(), e);
            return null;
        }
        return execute;
    }
}